#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: tapd_to_xmind_ui.py
# Author: ChenChangSong
# Date: 2025-08-24

"""
功能描述: TAPD→XMind 页面 UI。
"""
from PyQt5.QtWidgets import (
    QFileDialog,
    QGridLayout,
    QLabel,
    QTreeWidget,
    QTreeWidgetItem,
    QPushButton,
    QVBoxLayout,
    QWidget,
    QHeaderView,
    QAbstractItemView,
    QHBoxLayout,
    QMessageBox
)
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QFontMetrics

from .common_ui import LogPanel
from function_code.tapd_to_xmind.get_tapd_case_dir import get_tapd_case_directories
from function_code.tapd_to_xmind.tapd_export_xmind import tapd_export_xmind


class TapdToXmindPage(QWidget):
    def __init__(self) -> None:
        super().__init__()
        self._init_ui()
        self.dir_data = {}  # 存储目录ID和路径的映射
        self.selected_dir_id = None
        self.output_dir = None

    def _init_ui(self) -> None:
        root = QVBoxLayout(self)
        root.setSpacing(10)
        root.addWidget(QLabel("说明：此处的功能是将TAPD中的用例导出为Xmind文件。操作步骤：\n"
        "1、获取TAPD用例目录。2、选择下方要导出的用例目录。3、选择导出目录。4、导出为Xmind文件。"))

        grid = QGridLayout()
        grid.setHorizontalSpacing(10)
        grid.setVerticalSpacing(8)
        grid.setColumnStretch(1, 1)
        grid.setColumnStretch(3, 2)

        # 获取目录按钮
        self.btn_get_dir = QPushButton("获取TAPD用例目录")
        grid.addWidget(self.btn_get_dir, 0, 0)

        # 目录树 - 增加高度到原来的两倍
        self.tree_widget = QTreeWidget()
        self.tree_widget.setHeaderLabels(["目录名称", "目录ID"])
        self.tree_widget.header().setSectionResizeMode(0, QHeaderView.Stretch)
        self.tree_widget.header().setSectionResizeMode(1, QHeaderView.ResizeToContents)
        self.tree_widget.setSelectionMode(QAbstractItemView.SingleSelection)
        self.tree_widget.setMinimumHeight(600)  # 设置最小高度为600像素
        grid.addWidget(self.tree_widget, 1, 0, 8, 2)

        # 选择导出目录
        self.btn_choose_out = QPushButton("选择导出目录")
        self.btn_choose_out.setFixedSize(200, 40)
        self.lbl_out = QLabel("当前未选择导出目录")
        self.lbl_out.setWordWrap(False)
        self.lbl_out.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.lbl_out.setSizePolicy(self.lbl_out.sizePolicy().Expanding, self.lbl_out.sizePolicy().Fixed)
        
        # 创建水平布局放置选择目录按钮和路径显示
        out_dir_layout = QHBoxLayout()
        out_dir_layout.addWidget(self.btn_choose_out)
        out_dir_layout.addWidget(self.lbl_out)
        grid.addLayout(out_dir_layout, 7, 2, 1, 2)  # 向下移动到第7行

        # 导出按钮
        self.btn_export = QPushButton("导出为Xmind文件")
        self.btn_export.setFixedSize(200, 40)  # 增加宽度以确保文字完整显示
        grid.addWidget(self.btn_export, 8, 2, 1, 2)  # 向下移动到第8行

        root.addLayout(grid)

        # 日志面板 - 减少高度
        self.log_panel = LogPanel()
        root.addWidget(self.log_panel, 1)  # 添加伸缩因子，让日志面板占用剩余空间

        # 连接信号和槽
        self.btn_choose_out.clicked.connect(self._choose_out_dir)
        self.btn_get_dir.clicked.connect(self._load_dirs)
        self.btn_export.clicked.connect(self._export_xmind)
        self.tree_widget.itemSelectionChanged.connect(self._on_item_selected)

    def _choose_out_dir(self) -> None:
        path = QFileDialog.getExistingDirectory(self, "选择导出目录", "")
        if path:
            self.output_dir = path
            self._update_out_label()

    def _load_dirs(self) -> None:
        # 清空屏幕日志
        self.log_panel.clear_screen_logs()
        self.tree_widget.clear()
        self.dir_data = {}
        
        try:
            # 获取目录信息 - 注意：get_tapd_case_directories() 只返回一个值（目录字典）
            dir_dict = get_tapd_case_directories()
            if dir_dict is None:
                self.log_panel.append_log("获取目录失败或没有找到目录，请重试")
                return
                
            if not dir_dict:
                self.log_panel.append_log("获取目录失败或没有找到目录，请重试")
                return
                
            # 构建目录树
            root_nodes = {}
            
            for full_path, dir_id in dir_dict.items():
                
                # 分割路径为各级目录
                path_parts = full_path.split('-')
                
                # 构建树结构
                current_parent = None
                current_path = ""
                
                for i, part in enumerate(path_parts):
                    current_path = current_path + "-" + part if current_path else part
                    node_id = dir_dict.get(current_path, "")
                    
                    # 检查节点是否已存在
                    if current_path in root_nodes:
                        current_parent = root_nodes[current_path]
                        continue
                    
                     # 只创建两列的节点：目录名称和目录ID
                    node = QTreeWidgetItem([part, node_id])
                    
                    # 存储节点引用
                    root_nodes[current_path] = node
                    
                    # 添加到树中
                    if current_parent:
                        current_parent.addChild(node)
                    else:
                        self.tree_widget.addTopLevelItem(node)
                    
                    current_parent = node
            
            # 展开第一级目录
            for i in range(self.tree_widget.topLevelItemCount()):
                self.tree_widget.topLevelItem(i).setExpanded(True)
                
            self.log_panel.append_log(f"成功加载 {len(dir_dict)} 个目录")
            
        except Exception as e:
            self.log_panel.append_log(f"获取目录失败: {str(e)}")

    def _on_item_selected(self) -> None:
        selected_items = self.tree_widget.selectedItems()
        if selected_items:
            item = selected_items[0]
            dir_id = item.text(1)  # 第二列是目录ID
            if dir_id:  # 只有叶子节点才有目录ID
                self.selected_dir_id = dir_id
                dir_name = item.text(0)
                self.log_panel.append_log(f"已选择目录: {dir_name} (ID: {dir_id})")
            else:
                self.selected_dir_id = None
                self.log_panel.append_log("请选择具体目录(非父级目录)")

    def _export_xmind(self) -> None:
        if not self.selected_dir_id:
            QMessageBox.warning(self, "提示", "请先选择一个目录")
            return
            
        if not self.output_dir:
            QMessageBox.warning(self, "提示", "请先选择导出目录")
            return
            
        try:
            selected_item = self.tree_widget.selectedItems()[0]
            dir_name = selected_item.text(0)
            
            self.log_panel.append_log(f"开始导出目录 '{dir_name}' 的用例...")
            
            # 调用导出函数
            success = tapd_export_xmind(self.selected_dir_id, self.output_dir)
            
            if success:
                self.log_panel.append_log(f"成功导出目录 '{dir_name}' 的用例到 {self.output_dir}")
            else:
                self.log_panel.append_log(f"导出目录 '{dir_name}' 的用例失败")
                
        except Exception as e:
            self.log_panel.append_log(f"导出失败: {str(e)}")

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self._update_out_label()

    def _update_out_label(self) -> None:
        full = self.output_dir or ""
        if not full:
            self.lbl_out.setText("当前未选择导出目录")
            return
        self.lbl_out.setToolTip(full)
        metrics = QFontMetrics(self.lbl_out.font())
        available = max(80, self.lbl_out.width() - 8)
        elided = metrics.elidedText(full, Qt.ElideMiddle, available)
        self.lbl_out.setText(elided)